package com.das.mechanic_base.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.VibrateHelp;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3EdittextWatcher;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.hjq.toast.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.zyyoona7.wheel.WheelView;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class X3NewBottomMileOrTimeDialog extends X3BaseBottomSheetDialog implements ViewPager.OnPageChangeListener, View.OnClickListener, X3BaseBottomSheetDialog.IOnHideKey {

    private Point mScreenPoint = new Point();
    private View v_line;
    private TabLayout tb_layout;
    private ViewPager vp_view;
    private TextView tv_btn;

    private String[] title;

    private List<View> fragList;
    private int lastIndex = -1;

    // 选择保养总里程
    private List<Integer> mileList;
    private AloneServiceListBean listBean;
    private String moneyUnit;
    private int currentMiles;
    private int recommendSafeMiles;
    private double perMiles;

    /**
     * 设置的新当前里程
     */
    private int newCurrentMiles;

    /**
     * 时间计算方式的保养总里程
     */
    private int newTimeCurrentMiles;

    /**
     * 按总里程计算的时间
     */
    private String nextMilesTime;

    /**
     * 按时间模式计算的时间
     */
    private String nextAllTime;

    /**
     * 选择保养时间 年
     */
    private List<Integer> yearList = new ArrayList<>();

    private String date;

    /**
     * 选择月份
     */
    private List<String> monthList = new ArrayList<>();
    private int month;
    private int year;
    private int currentDay;

    /**
     * 是否修改了保养里程
     */
    private boolean isSave = false;

    /**
     * 是否是检测
     */
    private boolean isAlone;
    private int end;
    private TextView number_1;
    private TextView number_2;
    private TextView number_3;
    private TextView number_4;
    private TextView number_5;
    private TextView number_6;
    private TextView number_7;
    private TextView number_8;
    private TextView number_9;
    private TextView number_0;
    private RelativeLayout rl_delete;
    private TextView tv_confirm;
    private TextView number_00;
    private RelativeLayout rl_close;
    private X3KeyBoardDialog keyBoardDialog;
    private int type = 0;
    private boolean isAniOne =true;
    private boolean isAniTwo =true;
    private EditText et_input;
    private LinearLayout ll_toastmile;
    private AnimatorSet keyHide,keyShow;

    public X3NewBottomMileOrTimeDialog(@NonNull Context context, int type) {
        super(context);
        this.type = type;

    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        v_line = getView(R.id.v_line);
        tb_layout = getView(R.id.tb_layout);
        vp_view = getView(R.id.vp_view);
        initMiles();

        this.setiOnHideKey(this);

        title = new String[]{mContext.getString(R.string.x3_mile_set_value), mContext.getString(R.string.x3_time_set_value)};


        for (int i = 0; i < title.length; i++) {
            tb_layout.addTab(tb_layout.newTab().setText(title[i]));
        }

        yearList = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);

        for (int i = 49;i >= 1;i--){
            yearList.add(year - i);
        }

        for (int i = 0; i <= 50; i++) {
            yearList.add((year + i));
        }
        monthList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.select_month)));

        for (int i = 0; i < monthList.size(); i++) {
            String s = monthList.get(i);
            monthList.remove(i);
            monthList.add(i, s + " " + mContext.getString(R.string.plan_month));
        }

        moneyUnit = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");

        fragList = new ArrayList<>();
        fragList.add(View.inflate(mContext, R.layout.x3_fragment_mile_set_value_new, null));
        fragList.add(View.inflate(mContext, R.layout.x3_fragment_time_set_value_new, null));

        MileOrTimeAdapter mileOrTimeAdapter = new MileOrTimeAdapter(fragList, this);
        vp_view.setAdapter(mileOrTimeAdapter);
        vp_view.addOnPageChangeListener(this);

        tb_layout.setupWithViewPager(vp_view);
    }

    private void initMiles() {
        mileList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            mileList.add(i * 100);
        }

        for (int i = 1; i < 100; i++) {
            mileList.add(i * 1000);
        }

        for (int i = 10; i <= 100; i++) {
            mileList.add(i * 10000);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_bottom_mile_or_time_item;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        startAnim(position);
    }

    /**
     * 背景白快动画
     *
     * @param position
     */
    private void startAnim(int position) {
        if (lastIndex == position) {
            return;
        }
        Animation animation = v_line.getAnimation();
        if (animation != null) {
            animation.cancel();
        }

        end = 0;
        if (position == 0) {
            end = -X3ScreenUtils.dipToPx(6, mContext);
            v_line.animate().translationX(end).setDuration(200).start();
        } else {
            v_line.post(() -> {
                end = X3ScreenUtils.getScreenWidth(mContext) - v_line.getWidth() + X3ScreenUtils.dipToPx(6, mContext);
                v_line.animate().translationX(end).setDuration(200).start();
            });
        }

        lastIndex = position;
    }

    /**
     * 检测调整当前总里程
     *
     * @param listBean
     */
    public void showCurrentMile(AloneServiceListBean listBean, String remindType) {
        this.isAlone = true;
        this.listBean = listBean;
        this.currentMiles = (int) listBean.getCurrentMiles();
        this.recommendSafeMiles = (int) listBean.getRecommendSafeMiles();
        this.perMiles = listBean.getPerMiles();
        this.newCurrentMiles = recommendSafeMiles;
        this.newTimeCurrentMiles = recommendSafeMiles;
        if ("TIME".equals(remindType)) {
            vp_view.setCurrentItem(1);
            //v_line.setTranslationX(ScreenUtils.getScreenWidth(mContext) - v_line.getWidth());
        } else {
            vp_view.setCurrentItem(0);
            //v_line.setTranslationX(-ScreenUtils.dipToPx(6,mContext));
        }
    }

    /**
     * 与h5联调 修复保养总里程
     */
    public void modifyCurrentMiles(double currentMile, double perMiles, double nextReplaceCycleKm, String remindType, String date) {
        this.isAlone = false;
        this.currentMiles = (int) currentMile;
        this.perMiles = perMiles;
        this.recommendSafeMiles = (nextReplaceCycleKm < currentMile) ? currentMiles : (int) nextReplaceCycleKm;
        this.newCurrentMiles = recommendSafeMiles;
        this.newTimeCurrentMiles = recommendSafeMiles;
        this.date = date;
        if ("TIME".equals(remindType)) {
            vp_view.setCurrentItem(1);
        } else {
            vp_view.setCurrentItem(0);
        }
    }

    @Override
    public void dismiss() {
        if (v_line.getAnimation() != null) {
            v_line.getAnimation().cancel();
        }
        if (!isSave) {
            if (iOnAffirmSelect != null) {
                iOnAffirmSelect.iOnPickerDismiss();
            }
        }
        if (delHandler != null) {
            delHandler.removeCallbacks(delRun);
        }
        super.dismiss();
    }

    IOnAffirmSelect iOnAffirmSelect;

    public void setiOnAffirmSelect(IOnAffirmSelect iOnAffirmSelect) {
        this.iOnAffirmSelect = iOnAffirmSelect;
    }

    /**
     * 手动触发了 隐藏软键盘
     */
    @Override
    public void iOnHideKeyBoard() {

    }

    public interface IOnAffirmSelect {

        void iOnAffirmMiles(AloneServiceListBean sn);

        void iOnPickerDismiss();

    }

    IOnAffirmMile iOnAffirmMile;

    public void setiOnAffirmMile(IOnAffirmMile iOnAffirmMile) {
        this.iOnAffirmMile = iOnAffirmMile;
    }

    public interface IOnAffirmMile {
        void iOnAffirmMileAndTime(String time, String nextMiles, int type);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {


        }
    }
    boolean isShow =true;
    class MileOrTimeAdapter extends PagerAdapter implements View.OnClickListener {
        private List<View> mList;
        private X3NewBottomMileOrTimeDialog mileOrTimeDialog;
        private String monthindex;
        private int afterDay;
        private int afterDay1;
        private int afterDayTime1;
        private TextView tv_mile_exceed;

        public MileOrTimeAdapter(List<View> mList, X3NewBottomMileOrTimeDialog mileOrTimeDialog) {
            this.mList = mList;
            this.mileOrTimeDialog = mileOrTimeDialog;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view = mList.get(position);

            int remailCurrentMile = recommendSafeMiles - currentMiles;
            if (remailCurrentMile < 0) {
                remailCurrentMile = 0;
            }
            if (perMiles == 0.0 || perMiles == 0.00) {
                afterDay = 0;
            } else {
                afterDay = X3StringUtils.getInt(remailCurrentMile / perMiles);
            }
            if (afterDay < 0) {
                afterDay = 0;
            }
            if (position == 0) {
                et_input = view.findViewById(R.id.et_input);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    et_input.setShowSoftInputOnFocus(false);
                }
//                et_input.setCursorVisible(true);
//                et_input.requestFocus();
//                X3Utils.hideSoftInputMethod(mContext,et_input);
//                et_input.setInputType(InputType.TYPE_NULL);

                tv_mile_exceed = view.findViewById(R.id.tv_mile_exceed);
                TextView tv_one = view.findViewById(R.id.tv_one);
                TextView tv_two = view.findViewById(R.id.tv_two);
                TextView tv_three = view.findViewById(R.id.tv_three);
                TextView tv_four = view.findViewById(R.id.tv_four);
                tv_one.setText(String.format(mContext.getString(R.string.time_or_time_after),"5000"+moneyUnit));
                tv_two.setText(String.format(mContext.getString(R.string.time_or_time_after),"10000"+moneyUnit));
                tv_three.setText(String.format(mContext.getString(R.string.time_or_time_after),"15000"+moneyUnit));
                tv_four.setText(String.format(mContext.getString(R.string.time_or_time_after),"20000"+moneyUnit));

                TextView tv_unit = view.findViewById(R.id.tv_unit);
                TextView tv_notice = view.findViewById(R.id.tv_notice);
//                WheelView<Integer> wv_mile = view.findViewById(R.id.wv_mile);
                TextView tv_num = view.findViewById(R.id.tv_num);
                TextView tv_mile = view.findViewById(R.id.tv_mile);
                TextView tv_time = view.findViewById(R.id.tv_time);
                ImageView iv_delete = view.findViewById(R.id.iv_delete);
                TextView tv_now = view.findViewById(R.id.tv_now);
                ll_toastmile = view.findViewById(R.id.ll_toastmile);
                number_1 =  view.findViewById(R.id.number_1);
                number_2 =  view.findViewById(R.id.number_2);
                number_3 =  view.findViewById(R.id.number_3);
                number_4 =  view.findViewById(R.id.number_4);
                number_5 =  view.findViewById(R.id.number_5);
                number_6 =  view.findViewById(R.id.number_6);
                number_7 =  view.findViewById(R.id.number_7);
                number_8 =  view.findViewById(R.id.number_8);
                number_9 =  view.findViewById(R.id.number_9);
                number_0 =  view.findViewById(R.id.number_0);
                number_00 = view.findViewById(R.id.number_00);
                rl_close =  view.findViewById(R.id.rl_close);
                rl_delete = view.findViewById(R.id.rl_delete);
                tv_btn = view.findViewById(R.id.tv_btn);
                RelativeLayout rl_keyboard = view.findViewById(R.id.rl_keyboard);
                rl_keyboard.setOnClickListener(v -> {
                });
                tv_btn.setOnClickListener(this);
                int finalrecommendSafeMiles = currentMiles;
                double finalperMiles = perMiles;

                showKeyboard(rl_keyboard, tv_mile_exceed, finalperMiles, tv_mile, tv_time);

                RelativeLayout rl_container =  view.findViewById(R.id.rl_container);
                rl_container.setOnClickListener(v -> {
                    if (rl_keyboard.getTranslationY() == 0) {
                        showKeyboard(rl_keyboard, tv_mile_exceed, finalperMiles, tv_mile, tv_time);
                    }
                });

                tv_confirm =  view.findViewById(R.id.tv_confirm);
                number_1.setOnClickListener(v -> {
                    shock();
                    addInputData("1");
                });
                number_2.setOnClickListener(v -> {
                    shock();
                    addInputData("2");
                });
                number_3.setOnClickListener(v -> {
                    shock();
                    addInputData("3");
                });
                number_4.setOnClickListener(v -> {
                    shock();
                    addInputData("4");
                });
                number_5.setOnClickListener(v -> {
                    shock();
                    addInputData("5");
                });
                number_6.setOnClickListener(v -> {
                    shock();
                    addInputData("6");
                });
                number_7.setOnClickListener(v -> {
                    shock();
                    addInputData("7");
                });
                number_8.setOnClickListener(v -> {
                    shock();
                    addInputData("8");
                });
                number_9.setOnClickListener(v -> {
                    shock();
                    addInputData("9");
                });
                number_0.setOnClickListener(v -> {
                    shock();
                    addInputData("0");
                });
                number_00.setOnClickListener(v -> {
                    shock();
                    addInputData("00");

                });
                rl_close.setOnClickListener(v -> {
                    if (rl_keyboard.getTranslationY() == 0) {
                        showKeyboard(rl_keyboard, tv_mile_exceed, finalperMiles, tv_mile, tv_time);
                    }
                });
                rl_delete.setOnClickListener(v -> {
                    if (X3StringUtils.isEmpty(et_input.getText().toString())) {
                        return;
                    }
                    shock();

                    int  keyCode = KeyEvent.KEYCODE_DEL;

                    KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);

                    KeyEvent keyEventUp = new KeyEvent(KeyEvent.ACTION_UP, keyCode);

                    et_input.onKeyDown(keyCode, keyEventDown);

                    et_input.onKeyUp(keyCode, keyEventUp);
                });

                rl_delete.setOnLongClickListener(v -> {
                    delHandler.post(delRun);
                    return false;
                });

                tv_confirm.setOnClickListener(v -> {
                    shock();
                    if (rl_keyboard.getTranslationY() == 0) {
                        showKeyboard(rl_keyboard, tv_mile_exceed, finalperMiles, tv_mile, tv_time);
                    }
                });

                tv_now.setOnClickListener(v -> {
                    int data = finalrecommendSafeMiles;
                    et_input.setText(data + "");
                    et_input.setSelection(String.valueOf(data).length());
                    changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);
                });

                iv_delete.setOnClickListener(v -> {
                    et_input.setText("");
                    cuteMileAndTime(tv_mile_exceed,currentMiles,tv_mile,tv_time);
                });

                tv_one.setOnClickListener(v -> {
                    int data = 5000 + finalrecommendSafeMiles;
                    et_input.setText(data + "");
                    et_input.setSelection(String.valueOf(data).length());
                    changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);
                });
                tv_two.setOnClickListener(v -> {
                    int data = 10000 + finalrecommendSafeMiles;
                    et_input.setText(data + "");
                    et_input.setSelection(String.valueOf(data).length());
                    changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);

                });
                tv_three.setOnClickListener(v -> {
                    int data = 15000 + finalrecommendSafeMiles;
                    et_input.setText(data + "");
                    et_input.setSelection(String.valueOf(data).length());
                    changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);

                });

                tv_four.setOnClickListener(v -> {
                    int data = 20000 + finalrecommendSafeMiles;
                    et_input.setText(data + "");
                    et_input.setSelection(String.valueOf(data).length());
                    changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);

                });

                et_input.setOnClickListener(v -> {
                    if (rl_keyboard.getTranslationY() != 0) {
                        showKeyboard(rl_keyboard, tv_mile_exceed,finalperMiles,tv_mile,tv_time);
                    }
                });

                if (recommendSafeMiles < currentMiles) {
                    recommendSafeMiles = currentMiles;
                }

                et_input.setText(recommendSafeMiles + "");
                et_input.setSelection((recommendSafeMiles + "").length());
                tv_num.setText(recommendSafeMiles + "");
                tv_unit.setText(moneyUnit);
                changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);
                int i = mileList.indexOf(recommendSafeMiles);
                if (i < 0) {
                    mileList.add(recommendSafeMiles);
                    Collections.sort(mileList);
                    i = mileList.indexOf(recommendSafeMiles);
                }

                String addDaysMonth = X3DateUtils.getShowTime(date);

                if (afterDay == 0) {
                    nextMilesTime = year + "-" + ((month < 10) ? "0" + month : month);
                } else {
                    nextMilesTime = String.format(mContext.getString(R.string.x3_expect_miles_time), addDaysMonth);
                }

                et_input.setOnEditorActionListener((v, actionId, event) -> {
                    InputMethodManager im = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(et_input.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                });

                et_input.addTextChangedListener(new X3EdittextWatcher() {
                    @Override
                    protected void textInputAfter(String content) {
                        iv_delete.setVisibility(X3StringUtils.isEmpty(content) ? View.INVISIBLE : View.VISIBLE);
                        if(X3StringUtils.isEmpty(content)){
                            tv_mile_exceed.setVisibility(View.GONE);
                            et_input.setHint("" + currentMiles);
                            return;
                        }
                        String s = et_input.getText().toString();
                        if (X3StringUtils.isEmpty(s) || !X3StringUtils.isNumber(s)) {
                            ToastUtils.show(mContext.getString(R.string.x3_number_error));
                           return;
                        }
                        int data = Integer.parseInt(s);
                        if (data >= 2 * recommendSafeMiles && data > 100000) {
                            tv_mile_exceed.setVisibility(View.VISIBLE);
                        } else {
                            tv_mile_exceed.setVisibility(View.GONE);
                        }

                        changeData(Integer.parseInt(et_input.getText().toString()), et_input,finalperMiles,tv_mile,tv_time);
                    }
                });

            } else {
                TextView tv_month = view.findViewById(R.id.tv_month);
                TextView tv_notice = view.findViewById(R.id.tv_notice);
                WheelView<Integer> wv_year = view.findViewById(R.id.wv_year);
                WheelView<String> wv_month = view.findViewById(R.id.wv_month);

                wv_year.setVisibleItems(6);
                wv_year.setTypeface(ResourcesCompat.getFont(mContext, R.font.pingfan_bold));
                wv_year.setData(yearList);

                wv_month.setVisibleItems(6);
                wv_month.setTypeface(ResourcesCompat.getFont(mContext, R.font.pingfan_bold));
                wv_month.setData(monthList);
                TextView tv_years = view.findViewById(R.id.tv_years);
                TextView tv_months = view.findViewById(R.id.tv_months);
                TextView tv_time = view.findViewById(R.id.tv_time);
                TextView tv_mile = view.findViewById(R.id.tv_mile);
                TextView tv_one = view.findViewById(R.id.tv_one);
                TextView tv_two = view.findViewById(R.id.tv_two);
                TextView tv_three = view.findViewById(R.id.tv_three);
                TextView tv_four = view.findViewById(R.id.tv_four);
                TextView years = view.findViewById(R.id.years);
                years.setVisibility(LanguageUtiles.isZhRCN() ? View.VISIBLE : View.INVISIBLE);

                tv_two.setText(mContext.getString(R.string.month_after));
                tv_three.setText(mContext.getString(R.string.half_year_after));
                tv_four.setText(mContext.getString(R.string.one_year_after));

                tv_btn = view.findViewById(R.id.tv_btn);
                tv_btn.setOnClickListener(this);
                recommendSafeMiles = X3StringUtils.getInt(currentMiles + afterDay * perMiles);
                cucluteTime(afterDay,recommendSafeMiles,tv_time,wv_year,wv_month,tv_years,tv_months,tv_mile);
                tv_one.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tv_time.setText(mContext.getString(R.string.x3_now_to_work));
                        nextAllTime = year + "-" + ((month < 10) ? "0" + month : month);
                        wv_year.setSelectedItemPosition(0);
                        wv_month.setSelectedItemPosition(month - 1);
                        tv_mile.setText("");
                    }
                });
                tv_two.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int newMonth = month + 2;
                            //当前时间
                            if(newMonth <= 11){
                                wv_year.setSelectedItemPosition(yearList.indexOf(year));
                                wv_month.setSelectedItemPosition(newMonth);
                            }else {
                                wv_year.setSelectedItemPosition(yearList.indexOf(year + newMonth / 12));
                                wv_month.setSelectedItemPosition(newMonth % 12);
                            }
                    }
                });
                tv_three.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int newMonth = month + 5;
                        //当前时间
                        if(newMonth <= 11){
                            wv_year.setSelectedItemPosition(yearList.indexOf(year));
                            wv_month.setSelectedItemPosition(newMonth);
                        }else {
                           int a = newMonth % 12;
                            wv_year.setSelectedItemPosition(yearList.indexOf(year + newMonth / 12));
                            wv_month.setSelectedItemPosition(newMonth % 12);
                        }
                    }
                });

                tv_four.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //当前时间
                        wv_year.setSelectedItemPosition(yearList.indexOf(year+1));
                        wv_month.setSelectedItemPosition(month - 1);

                    }
                });

//                if (LanguageUtiles.isZhRCN()) {
//                    if (StringUtils.isEmpty(date)) {
//                        wv_year.setSelectedItemPosition(yearList.indexOf(year));
//                        wv_month.setSelectedItemPosition(monthList.indexOf((month < 10 ? "0" + month : month) + " " + mContext.getString(R.string.plan_month)));
//                    } else {
//                        String[] split = date.split("-");
//                        if (split != null && split.length >= 2) {
//                            wv_year.setSelectedItemPosition(yearList.indexOf(Integer.parseInt(split[0])));
//                            wv_month.setSelectedItemPosition(monthList.indexOf(split[1] + " " + mContext.getString(R.string.plan_month)));
//                        }
//                        Log.e("SSSS", "选中的" + split[0] + "::" + split[1]);
//                    }
//                } else {
//                    if (StringUtils.isEmpty(date)) {
//                        wv_year.setSelectedItemPosition(yearList.indexOf(year));
//                        wv_month.setSelectedItemPosition(monthList.indexOf(month + " " + mContext.getString(R.string.plan_month)));
//                        Log.e("SSSS", "选中的asdkjfakl;f");
//                    } else {
//                        String[] split = date.split("-");
//                        if (split != null && split.length >= 2) {
//                            wv_year.setSelectedItemPosition(yearList.indexOf(Integer.parseInt(split[0])));
//                            if (split[1].startsWith("0")) {
//                                monthindex = split[1].substring(1, 2);
//                            } else {
//                                monthindex = split[1];
//                            }
//                            if (Integer.parseInt(monthindex) > 0) {
//                                wv_month.setSelectedItemPosition((Integer.parseInt(monthindex) - 1));
//                            }
//                        }
//                    }
//                }


//                if (LanguageUtiles.isZhRCN()) {
//                    nextAllTime = wv_year.getSelectedItemData() + "-" + wv_month.getSelectedItemData();
//                } else {
//                    for (int i = 0; i < monthList.size(); i++) {
//                        if (monthList.get(i).equals(wv_month.getSelectedItemData())) {
//                            int a = i + 1;
//                            nextAllTime = wv_year.getSelectedItemData() + "-" + (a < 10 ? "0" + a : a);
//                        }
//                    }
//                }
                wv_year.setOnItemSelectedListener((wheelView, data, position12) -> {
                    if (data == year) {
                        // 等于当前年的时候 需要判断选择的月份是否比当前月份小 如果小的话 需要将月份自动选择为当前月
                        int selectedItemPosition = wv_month.getSelectedItemPosition();
                        if (selectedItemPosition + 1 < month) {
                            wv_month.setSelectedItemPosition(month - 1);
                        }
                    }
                    //                    // 获取年月 计算时间
                    int selectedItemPosition = wv_month.getSelectedItemPosition();
                    String selectMonth = (selectedItemPosition + 1) < 10 ? "0" + (selectedItemPosition + 1) : (selectedItemPosition + 1) + "";
                    String selectTime = data + "-" + selectMonth + "-01";
                    try {
                        int gapCount = X3DateUtils.getGapCount(new Date(System.currentTimeMillis()), X3DateUtils.stringToDate(selectTime, "yyyy-MM-dd"));
                        String[] selectTimes = selectTime.split("-");
                        wv_year.setSelectedItemPosition(yearList.indexOf(Integer.parseInt(selectTimes[0])));
                        wv_month.setSelectedItemPosition(monthList.indexOf(selectTimes[1]));
                        cucluteTime(gapCount, X3StringUtils.getInt(currentMiles + perMiles * gapCount),tv_time,wv_year,wv_month,tv_years,tv_months,tv_mile);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    if (LanguageUtiles.isZhRCN()) {
                        nextAllTime = wv_year.getSelectedItemData() + "-" + wv_month.getSelectedItemData();
                    } else {

                        for (int i = 0; i < monthList.size(); i++) {
                            if (monthList.get(i).equals(wv_month.getSelectedItemData())) {
                                int a = i + 1;
                                nextAllTime = wv_year.getSelectedItemData() + "-" + (a < 10 ? "0" + a : a);
                            }
                        }
                    }
                });

                wv_month.setOnItemSelectedListener((wheelView, data, position13) -> {
                    int selectedItemPosition = wv_year.getSelectedItemPosition();
                    if (selectedItemPosition == 0) {
                        if (position13 + 1 < month) {
                            wv_month.setSelectedItemPosition(month - 1);
                        }
                    }
                    if (LanguageUtiles.isZhRCN()) {
                        nextAllTime = wv_year.getSelectedItemData() + "-" + wv_month.getSelectedItemData();
                    } else {
                        for (int i = 0; i < monthList.size(); i++) {
                            if (monthList.get(i).equals(wv_month.getSelectedItemData())) {
                                int a = i + 1;
                                nextAllTime = wv_year.getSelectedItemData() + "-" + (a < 10 ? "0" + a : a);
                            }
                        }
                    }
                    String selectMonth = (position13 + 1) < 10 ? "0" + (position13 + 1) : (position13 + 1) + "";
                    String selectTime = wv_year.getSelectedItemData() + "-" + selectMonth + "-01";
                    try {
                        int gapCount = X3DateUtils.getGapCount(new Date(System.currentTimeMillis()), X3DateUtils.stringToDate(selectTime, "yyyy-MM-dd"));

//                        String[] selectTimes = selectTime.split("-");
                         cucluteTime(gapCount, X3StringUtils.getInt(currentMiles + perMiles * gapCount),tv_time,wv_year,wv_month,tv_years,tv_months,tv_mile);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                });
            }

            container.addView(view);
            return view;
        }

        private void addInputData(String s) {
            long roomInput = Long.parseLong(et_input.getText().toString() + s);
            et_input.setText(roomInput + "");
            String content = et_input.getText().toString();
            et_input.setSelection(content.length());
        }

        public void showKeyboard(RelativeLayout rl_keyboard,TextView tv_mile_exceed,double finalperMiles,TextView tv_mile,TextView tv_time){
            rl_keyboard.post(new Runnable() {
                @Override
                public void run() {
                    if (rl_keyboard.getTranslationY() == 0) {
                        if (keyHide == null) {
                            keyHide = new AnimatorSet();
                            ObjectAnimator keyBoardHide = ObjectAnimator.ofFloat(rl_keyboard,"TranslationY",0,rl_keyboard.getHeight());
                            ObjectAnimator toastMileHide = ObjectAnimator.ofFloat(ll_toastmile,"TranslationY",-rl_keyboard.getHeight() + X3ScreenUtils.dipToPx(80,mContext),0);
                            keyHide.play(keyBoardHide).with(toastMileHide);
                            keyHide.setDuration(200);
                        }
                        keyHide.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                isAniTwo = true;
                                isShow = true;
                                super.onAnimationEnd(animation);
                            }

                            @Override
                            public void onAnimationStart(Animator animation, boolean isReverse) {
                                isAniTwo = false;
                            }
                        });
                        keyHide.start();

                        // 计算下次保养剩余
                        cuteMileAndTime(tv_mile_exceed,finalperMiles,tv_mile,tv_time);

                    }else {
                        if (keyShow == null) {
                            keyShow = new AnimatorSet();
                            ObjectAnimator keyBoardShow = ObjectAnimator.ofFloat(rl_keyboard,"TranslationY",rl_keyboard.getHeight(),0);
                            ObjectAnimator toastMileShow = ObjectAnimator.ofFloat(ll_toastmile,"TranslationY",0,-rl_keyboard.getHeight() + X3ScreenUtils.dipToPx(80,mContext));
                            keyShow.play(keyBoardShow).with(toastMileShow);
                            keyShow.setDuration(200);
                        }
                        keyShow.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                isAniOne = true;
                                isShow = false;
                                super.onAnimationEnd(animation);
                            }

                            @Override
                            public void onAnimationStart(Animator animation, boolean isReverse) {
                                isAniOne = false;
                            }
                        });
                        keyShow.start();
                    }
                }
            });


        }

        private void cuteMileAndTime(TextView tv_mile_exceed,double finalperMiles,TextView tv_mile,TextView tv_time) {
            String roomInput = et_input.getText().toString();
            if (X3StringUtils.isEmpty(roomInput)) {
                tv_mile_exceed.setVisibility(View.GONE);
                X3ToastUtils.showMessage(mContext.getString(R.string.not_than_total_mile));
                return;
            }

            int data = Integer.parseInt(roomInput);
            if (data < currentMiles) {
                et_input.setHint("" + currentMiles);
                X3ToastUtils.showMessage(mContext.getString(R.string.not_than_total_mile));
                return;
            }

            if (data >= 2 * currentMiles && data > 100000) {
                tv_mile_exceed.setVisibility(View.VISIBLE);
            } else {
                tv_mile_exceed.setVisibility(View.GONE);
            }

            changeData(Integer.parseInt(et_input.getText().toString()),et_input,finalperMiles,tv_mile,tv_time);
        }

        /**
         * 计算按照保养总里程
         *
         * @param data
         * @param
         */
        private void culteMile(Integer data,Double perMiles,TextView tv_mile,TextView tv_time) {
            // 在这计算展示的数据
            int remainMiles = data - currentMiles;
            if (remainMiles < 0) {
                remainMiles = 0;
            }
            if (perMiles == 0.0) {
                afterDay1 = 0;
                afterDayTime1 = 0;
            } else {
                afterDay1 = (int) (remainMiles / perMiles);
                afterDayTime1 = (int) Math.ceil(remainMiles / perMiles);
            }

            if (afterDay1 < 0) {
                afterDay1 = 0;
            }
            if (afterDayTime1 < 0) {
                afterDayTime1 = 0;
            }

            if (afterDay1 == 0) {
                String frontText = mContext.getString(R.string.x3_now_to_work);
                tv_mile.setText(frontText);
                tv_time.setText(X3DateUtils.getAddDaysMonth(0)+"");
                nextMilesTime = year + "-" + ((month < 10) ? "0" + month : month);
            } else {
                String addDaysMonth = X3DateUtils.getAddDaysMonth(afterDayTime1);
                tv_mile.setText(remainMiles+moneyUnit);
                tv_time.setText(addDaysMonth+"");
                nextMilesTime = X3DateUtils.getSubmitTime(addDaysMonth+"");
            }
        }
        /**
         * 计算
         * @param afterDay
         * @param wv_year
         * @param wv_month
         */
        private void cucluteTime(int afterDay,int recommendMiles, TextView tv_time, WheelView<Integer> wv_year, WheelView<String> wv_month,TextView tv_years,TextView tv_months,TextView tv_mile) {
            // 计算当前里程的预计保养时间
            newTimeCurrentMiles = recommendMiles;

            if (afterDay < 0) {
                afterDay = 0;
            }
            try {
                long monthSpace1 = X3DateUtils.stringToLong("2020-10","yyyy-MM");
                long monthSpace2 = X3DateUtils.stringToLong("2021-09","yyyy-MM");
                long a = monthSpace2 - monthSpace1;
                long days =  a / (1000 * 60 * 60 * 24);
                long month = days / 30;

            } catch (ParseException e) {
                e.printStackTrace();
            }
            String addDaysMonth = X3DateUtils.getAddDaysMonth(afterDay);//2020年10月
            boolean isChina = LanguageUtiles.isZhRCN();
            if(isChina){
                tv_years.setText(addDaysMonth.substring(0,4)+"");
                tv_months.setText(addDaysMonth.substring(5,7)+"");

            }else {
                String[] split = addDaysMonth.split(",");
                if(split != null && split.length == 2){
                    tv_years.setText(split[0]+"");
                    tv_months.setText(split[1]+"");
                }

            }

            if (afterDay <= 0) {
                tv_time.setText(mContext.getString(R.string.x3_now_to_work));
                nextAllTime = year + "-" + ((month < 10) ? "0" + month : month);
                wv_year.setSelectedItemPosition(yearList.indexOf(year));
                wv_month.setSelectedItemPosition(month - 1);
                tv_mile.setText("");
            }else {
                nextAllTime = X3DateUtils.getSubmitTime(addDaysMonth);
                tv_time.setText(String.format(recommendMiles + moneyUnit));

                try {
                    if(isChina){
                        long monthSpace1 = X3DateUtils.stringToLong(year+"-"+month,"yyyy-MM");
                        long monthSpace2 = X3DateUtils.stringToLong(tv_years.getText().toString()+"-"+tv_months.getText().toString(),"yyyy-MM");
                        long a = monthSpace2 - monthSpace1;
                        long days =  a / (1000 * 60 * 60 * 24);
                        long month = days / 30;
                        if(month > 1){
                            tv_mile.setText(String.format(mContext.getString(R.string.how_match_months),month));
                        }else {
                            tv_mile.setText(String.format(mContext.getString(R.string.how_match_month),month));
                        }
                    }else {
                        long monthSpace1 = X3DateUtils.stringToLong(year+"-"+month,"yyyy-MM");
                        int m  = 0;

                        for (int i = 0; i < monthList.size();i++){
                            if(monthList.get(i).equals(tv_years.getText().toString()+" ")){
                                m = i;
                            }
                        }
                        String monthN = "";
                        int ms = m + 1;
                        if(ms < 10){
                            monthN = "0"+ms;
                        }else {
                            monthN = ms+"";
                        }
                        long monthSpace2 = X3DateUtils.stringToLong(tv_months.getText().toString()+"-"+ms,"yyyy-MM");
                        long a = monthSpace2 - monthSpace1;
                        long days =  a / (1000 * 60 * 60 * 24);
                        long month = days / 30;
                        if(month > 1){
                            tv_mile.setText(String.format(mContext.getString(R.string.how_match_months),month));
                        }else {
                            tv_mile.setText(String.format(mContext.getString(R.string.how_match_month),month));
                        }
                    }



                } catch (ParseException e) {
                    e.printStackTrace();
                }

                String showTime;
                if (LanguageUtiles.isZhRCN()) {
                    showTime = addDaysMonth.replace("年", ",").replace("月", "");
                    String[] split = showTime.split(",");
                    if (split != null && split.length >= 2) {
                        wv_year.setSelectedItemPosition(yearList.indexOf(Integer.parseInt(split[0])));
                        wv_month.setSelectedItemPosition(monthList.indexOf(split[1]+" " + mContext.getString(R.string.plan_month)));
                    }
                }else {
                    showTime = addDaysMonth.replace(" ","");
                    String[] split = showTime.split(",");
                    if (split != null && split.length >= 2) {
                        wv_year.setSelectedItemPosition(yearList.indexOf(Integer.parseInt(split[1])));
                        wv_month.setSelectedItemPosition(monthList.indexOf(split[0]));
                    }
                }
            }
        }
        public void changeData(Integer data, EditText et_input,double finalperMiles,TextView tv_mile,TextView tv_time) {
            if (data < currentMiles) {
                String frontText = mContext.getString(R.string.x3_now_to_work);
                tv_mile.setText(frontText);
                tv_time.setText(String.format(mContext.getString(R.string.x3_expect_miles_time), X3DateUtils.getAddDaysMonth(0)));
                nextMilesTime = year + "-" + ((month < 10) ? "0" + month : month);

            } else {
                culteMile(data, finalperMiles,tv_mile,tv_time);

            }
            newCurrentMiles = Integer.parseInt(et_input.getText().toString());
        }


        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return title[position];
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.tv_btn) {
                if (!isAlone) {
                    if (vp_view.getCurrentItem() == 0) {
                        if (iOnAffirmMile != null) {
                            iOnAffirmMile.iOnAffirmMileAndTime(nextMilesTime, newCurrentMiles + "", 0);

                        }
                    } else {
                        nextAllTime = nextAllTime.replace(" " + mContext.getString(R.string.plan_month), "");
                        if (iOnAffirmMile != null) {
                            iOnAffirmMile.iOnAffirmMileAndTime(nextAllTime, newTimeCurrentMiles + "", 1);
                        }
                    }
                    dismiss();
                    return;
                }

                /**
                 * 确定保养总里程
                 */
                int currentItem = vp_view.getCurrentItem();
                int allMiles;
                if (currentItem == 0) {
                    allMiles = newCurrentMiles;
                } else {
                    allMiles = newTimeCurrentMiles;
                }
                if (allMiles < currentMiles) {
                    allMiles = currentMiles;
                }

                isSave = true;
                if (currentItem == 0) {
                    String roomInput = et_input.getText().toString();
                    if (X3StringUtils.isEmpty(roomInput)) {
                        return;
                    }

                    int data = Integer.parseInt(roomInput);
                    if (data < newCurrentMiles) {
                        return;
                    }

                    if (allMiles >= 2 * recommendSafeMiles && allMiles > 100000) {
                        return;
                    }
                }


                /**
                 * TODO 更新数据库中的剩余保养里程
                 */
                listBean.setRecommendSafeMiles(allMiles);
                if (vp_view.getCurrentItem() == 0) {
                    listBean.setReductionType("MILE");
                    listBean.setWarningDate(X3DateUtils.getAloneSubmitTime(nextMilesTime));
                } else {
                    listBean.setReductionType("TIME");
                    nextAllTime = nextAllTime.replace(" " + mContext.getString(R.string.plan_month), "");
                    listBean.setWarningDate(X3DateUtils.getAloneSubmitTime(nextAllTime));
                }

                isSave = true;

                try {
                    if (type == 1) {//确定
                        X3ToastUtils.showMessage(mContext.getString(R.string.add_maintance_sus));
                    } else {//更新
                        X3ToastUtils.showMessage(mContext.getString(R.string.refresh_maintance_sus));
                    }
                    dismiss();
                    if (iOnAffirmSelect != null) {
                        iOnAffirmSelect.iOnAffirmMiles(listBean);
                    }

                } catch (Exception e) {
                }
            }
        }
    }

    private Handler delHandler = new Handler();

    private Runnable delRun = new Runnable() {
        @Override
        public void run() {
            int selectionStart = et_input.getSelectionStart();
            if (selectionStart > 0 && rl_delete.isPressed()) {
                rl_delete.performClick();
                delHandler.postDelayed(delRun,100);
            }else {
                delHandler.removeCallbacks(delRun);
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("双轨弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("双轨弹窗");
    }
    public void shock(){
        VibrateHelp.vSimple(mContext, 60);
    }


}